import * as Debug from "./Debug";
import { SyntaxPattern, type SentenceContent, SP, type SyntaxNode, N, VerbElement } from "./NarrativeBase";

export const NAlgorithms = {
    expressNumber(n: number) {
        const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        Debug.assert(n >= 0);
        if (n == 0) return '零';
        if (n >= 100) return n.toString();
        let a = Math.floor(n / 10), b = n % 10;
        return (a < 2 ? '' : digits[a]) + (n >= 10 ? '十' : '')
            + (b == 0 ? '' : digits[b]);
    },

    /**
     * @returns an adverbial node; currently complete with the comma after it
     */
    generateWhenClause(from: SentenceContent): SyntaxNode | null {
        let pattern = [SP.S('s'), SP.P('p').with(SP.any('a1').asterisk(), SP.V('v'), SP.any('a2').asterisk())];
        let map = SyntaxPattern.match(pattern, from);
        if (map) {
            let verb = map.get('v')![0] as VerbElement;
            verb.isPerfective = false;
            if (verb.isDurative)
                return N.ADV(N.PREP('在'), N.CL(
                    map.get('s')![0], map.get('p')![0]), N.POSTP('时，'));
            else
                return N.ADV(N.PREP('当'), N.CL(
                map.get('s')![0], N.ADV('正要'), map.get('p')![0]), N.POSTP('时，'));
        }
        return null;
    }
}
